/*
 * @Date: 2020-09-11 13:37:21
 * @LastEditors: 小枫
 * @LastEditTime: 2020-09-24 16:46:15
 * @FilePath: \feng-blog\app\middleware\authToken.ts
 */
import { Context } from 'egg';

// 自定义的中间件：验证token
export default function jwtAuth(options: any): any {
  return async (ctx: Context, next: () => Promise<any>) => {
    const token = ctx.request.headers.authorization;
    let decode: any = '';
    if (token) {
      try {
        // 解码token
        decode = await ctx.app.jwt.verify(token, options.secret);
        const now = new Date().valueOf();
        const timeDif = (now - (decode.iat * 1000)) / (60 * 60 * 1000); // 过期时间1天
        // console.log(now, timeDif, decode.iat);
        if (timeDif > 24) {
          ctx.status = 301;
          ctx.body = {
            msg: 'token过期',
          };
          return;
        }
        ctx.authUser = decode.uid;
        // console.log('====================================');
        // console.log(decode);
        // console.log('====================================');
        // console.log('decode======>', decode);
        await next();
      } catch (error) {
        ctx.status = 401;
        ctx.body = {
          msg: error.message,
        };
        return;
      }
    } else {
      ctx.status = 401;
      ctx.body = {
        msg: '没有token',
      };
      return;
    }
  };
}
